# coding=utf8
# 全世界最帅的帅哥
import jwt
from jwt import PyJWTError
from datetime import datetime, timedelta
from comment.utils.const import SECRET_KEY, JWT_EXPIRY_SECONDS
from flask import current_app
from comment.modules.user import User


def generate_tokens(uid):
    """
    一个用户在一次会话中生成一个TOKEN
    :param uid: 用户id
    :return:
    """

    params = {
        "id": uid,
        "expiry": str(datetime.utcnow() + timedelta(seconds=JWT_EXPIRY_SECONDS))
    }

    return jwt.encode(payload=params, key=SECRET_KEY, algorithm="HS256")


def verify_tokens(token):
    """
    验证token
    :param token:
    :return: 成功返回用户ID
    """

    try:
        # 返回之前生成token的一个字典
        data = jwt.decode(token, key=SECRET_KEY, algorithms="HS256")
        user = User.query.filter(User.id == data["id"]).first()
        if user and user.onlock == 0:
            return {"id": data["id"]}
        else:
            return {"message": "数据库中不存在当前用户，或者token过期"}

    except PyJWTError as e:
        current_app.logger.error(e)
        return {"message": "token验证失败"}
